package com.kc.business.service.impl;

import com.kc.business.domain.BizScenicBusinessType;
import com.kc.business.mapper.BizScenicBusinessTypeMapper;
import com.kc.business.service.IBizScenicBusinessTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author zhangshuo
 * @version 1.0
 * @date 2020/9/9
 */
@Service
public class BizScenicBusinessTypeServiceImpl implements IBizScenicBusinessTypeService {

    @Autowired
    BizScenicBusinessTypeMapper bizScenicBusinessTypeMapper;

    /**
     * 查询类别列表
     *
     * @param bizScenicBusinessType
     * @return
     */
    @Override
    public List<BizScenicBusinessType> getList(BizScenicBusinessType bizScenicBusinessType) {
        return bizScenicBusinessTypeMapper.select(bizScenicBusinessType);
    }

    /**
     * 新增类别
     *
     * @param bizScenicBusiness
     * @return
     */
    @Override
    public int add(BizScenicBusinessType bizScenicBusiness) {
        return bizScenicBusinessTypeMapper.insertSelective(bizScenicBusiness);
    }

    /**
     * 修改类别
     *
     * @param bizScenicBusiness
     * @return
     */
    @Override
    public int edit(BizScenicBusinessType bizScenicBusiness) {
        return bizScenicBusinessTypeMapper.updateByPrimaryKeySelective(bizScenicBusiness);
    }

    /**
     * 构建树形类别
     *
     * @param types 类别列表
     * @return 类别列表
     */
    public List<BizScenicBusinessType> buildTypes(List<BizScenicBusinessType> types) {
        // 2. 找出所有一级分类
        //    在映射到每个一级分类 添加它的子分类类
        return types.stream()
                .filter(o -> o.getPid() == 0)
                // 给每个一级分类加子分类
                .peek(o -> o.setChildren(getChildCategoryList(o, types)))
                // 排序
                .sorted(Comparator.comparingInt(BizScenicBusinessType::getSort))
                // 收集
                .collect(Collectors.toList());
    }

    // 根据当前分类 找出子类， 并通过递归找出子类的子类
    private List<BizScenicBusinessType> getChildCategoryList(BizScenicBusinessType currType, List<BizScenicBusinessType> types) {
        return types.stream().filter(o -> o.getPid().equals(currType.getId()))
                .peek(o -> o.setChildren(getChildCategoryList(o, types)))
                .sorted(Comparator.comparingInt(BizScenicBusinessType::getSort))
                .collect(Collectors.toList());
    }

}
